import { createRouter, createWebHistory } from 'vue-router'
import { GET_TOKEN } from '@/utils/token'
import nprogress from 'nprogress'
//引入进度条样式
import 'nprogress/nprogress.css'
nprogress.configure({ showSpinner: false })

const routes = [
  {
    path: '/',
    component: () => import('@/layout/index.vue'),
    name: 'layout',
    redirect: '/home',
    children: [
      {
        path: '/home',
        name: 'home',
        component: () => import('@/views/home/index.vue'),
        meta: {
          title: '首页',
          hidden: false
        }
      },
      {
        path: '/artclelist',
        name: 'Artclelist',
        meta: {
          title: '文章列表' //设置该路由在浏览器标签显示的title
        },
        props: (route) => {
          let query = route.query
          return { ...query }
        },
        component: () => import('@/views/artcle/index.vue')
      },
      {
        path: '/artcle/:id',
        name: 'ArtclePage',
        meta: {
          title: '文章详情页', //设置该路由在浏览器标签显示的title
          hidden: true
        },
        props: true,
        component: () => import('@/views/artcle/ArtclePage.vue'),
        beforeEnter: (to, from, next) => {
          console.log('路由独享的守卫:beforeEnter')
          next()
        }
      },
      {
        path: '/book',
        name: 'book',
        meta: {
          title: '书籍'
        },
        component: () => import('@/views/book/index.vue')
      }
    ]
  },
  {
    path: '/login',
    name: 'Login',
    meta: {
      title: '登录' //设置该路由在浏览器标签显示的title
    },
    component: () => import('@/views/login/index.vue')
  },
  {
    path: '/:catchAll(.*)',
    component: () => import('@/views/404/index.vue')
  }
]
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes
})
// 全局前置守卫
router.beforeEach((to, from, next) => {
  console.log('全局前置守卫:beforeEach')
  // 进度条开始
  nprogress.start()
  if (to?.meta?.title) {
    document.title = to.meta.title
  }
  // 在这里执行你的逻辑
  // 例如，检查用户是否登录
  const token = GET_TOKEN()

  if (!token) {
    if (to.path === '/login') {
      next()
    } else {
      next({ path: '/login' })
      nprogress.done()
    }
  } else {
    if (to.path === '/login') {
      next({ path: '/home' })
      nprogress.done()
      // return false
    } else {
      // 否则，继续导航
      next()
    }
  }
})
// 全局解析守卫
router.beforeResolve((to, from, next) => {
  console.log('全局解析守卫:beforeResolve')
  next() // 继续导航
})

//全局后置守卫
router.afterEach(() => {
  console.log('全局后置守卫:afterEach')
  nprogress.done()
})
export { routes }
export default router
